package cn.alcatraz.system.service.impl;


import cn.alcatraz.system.domain.Menu;
import cn.alcatraz.system.mapper.MenuMapper;
import cn.alcatraz.system.service.IMenuService;
import cn.alcatraz.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author alcatraz
 * @since 2022-07-11
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    MenuMapper menuMapper;

    /*@Override
    @Transactional
    public void save(Menu menu) {
        menuMapper.save(menu);
        //comPath拼接值
        String component = "";
        if (menu.getParent().getId() == null){
            component = "/" + menu.getId();
        }else {
            Menu parentMenu = menuMapper.loadById(menu.getParent().getId());
            if(parentMenu != null){
                component = parentMenu.getComponent() + "/" + menu.getId();
            }
        }
        menu.setComponent(component);
        menuMapper.update(menu);
    }*/
    /**
     * @Title: update
     * @Description: 拼接地址级
     * @Author: Alcatraz
     * @Version: 1.0
     * @Date:  2022/6/26 10:22
     * @Parameters: [menu]
     * @Return void
     */
    /*@Override
    @Transactional
    public void update(Menu menu) {
        //comPath拼接值
        String component = "";
        if (menu.getParent().getId() == null){
            component = "/" + menu.getId();
        }else {
            Menu parentDept = menuMapper.loadById(menu.getParent().getId());
            if(parentDept != null){
                component = parentDept.getComponent() + "/" + menu.getId();
            }
        }
        menu.setComponent(component);
        menuMapper.update(menu);
    }*/


    @Override
    public List<Menu> tree() {

        List<Menu> menus = menuMapper.loadAll();

        List<Menu> menuTree = new ArrayList<Menu>();

        HashMap<Long, Menu> menuMap = new HashMap<>();
        for (Menu menu : menus) {
            menuMap.put(menu.getId(), menu);
        }

        //从所有数据中找到一级数据
        for (Menu menuTmp : menus) {
            //数据没有父级Id，就是一级数据
            if(menuTmp.getParentId() == null){
                menuTree.add(menuTmp);
            }else {
                Menu menu = menuMap.get(menuTmp.getParentId());
                if (menu != null){
                    menu.getChildren().add(menuTmp);
                }
            }
        }
        return menuTree;
    }
}

